//
//  JVMonitorCenterHelper.m
//  AFNetworking
//
//  Created by 马泽岩 on 2018/2/26.
//

#import "JVMonitorCenterHelper.h"
#import <sqlite3.h>

@interface JVMonitorCenterHelper ()
{
    sqlite3 * db;
    NSString * appVersion;
}
@end

@implementation JVMonitorCenterHelper

+ (JVMonitorCenterHelper *)shareInstance {
    static JVMonitorCenterHelper *sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        [self openDB];
        NSDictionary * infoDict = [[NSBundle mainBundle] infoDictionary];
        appVersion = [infoDict objectForKey:@"CFBundleShortVersionString"];
    }
    return self;
}

#pragma ---------- private method -----------

- (NSString*)dbFilePath
{
    NSArray * pathList = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask,YES);
    NSString * parentPath = pathList[0];
    NSString * dbFilePath = [parentPath stringByAppendingString:@"/alog"];
    return dbFilePath;
}

- (void)openDB {
    NSString * dbFilePath = [self dbFilePath];
    if (sqlite3_open([dbFilePath UTF8String], &db) != SQLITE_OK) {
        sqlite3_close(db);
        db = nil;
    }
}

- (void)closeDB {
    if (db) {
        sqlite3_close(db);
        db = nil;
    }
}

- (BOOL)execSql:(NSString *)sql {
    char * err;
    if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err) != SQLITE_OK) {
        return NO;
    }
    return YES;
}

- (void)createTableWithDomain:(NSString *)domain {
    NSString * sql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ ( _id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT, app_version TEXT, timestamp INTEGER);",domain];
    [self execSql:sql];
}

- (NSString*)stringFromC:(const char *)cString
{
    if (cString && strlen(cString)>0) {
        return [[NSString alloc] initWithUTF8String:cString];
    }
    else{
        return @"";
    }
}

#pragma ---------- public method -----------

- (void)registerDomain:(NSString *)domain {
    [self createTableWithDomain:domain];
}

- (int64_t)insertData:(NSString *)data domain:(NSString *)domain {
    NSString *insertSQL = [NSString stringWithFormat:@"INSERT INTO %@ (data,app_version,timestamp) VALUES(?,?,?);",domain];
    sqlite3_stmt *stmt = nil;
    NSString *data_str = data?:@"";
    NSString *app_version = appVersion?:@"";
    NSTimeInterval curTime = [[NSDate date] timeIntervalSince1970];
    unsigned int curTime_unint = (unsigned int)(curTime);
    int prepareResult = sqlite3_prepare_v2(db,[insertSQL UTF8String],-1,&stmt,NULL);
    if ( prepareResult == SQLITE_OK ) {
        sqlite3_bind_text(stmt, 1, [data_str UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 2, [app_version UTF8String], -1, NULL);
        sqlite3_bind_int(stmt, 3, curTime_unint);
    }else{
        return -1;
    }
    
    if ( sqlite3_step(stmt) != SQLITE_DONE ) {
        sqlite3_finalize(stmt);
        return -1;
    }
    
    int64_t newid = sqlite3_last_insert_rowid(db);
    
    sqlite3_finalize(stmt);
    
    return newid;
}


/**
 * 搜索出所有的指定域下的数据
 * @param domain 指定的域
 * @param deleteData 查出之后删除数据
 */
- (NSArray<NSDictionary *> *)searchDataWithDomain:(NSString *)domain deleteData:(BOOL)deleteData {
    NSMutableArray *result = [NSMutableArray array];;
    
    NSString * sqlQuery = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY _id ASC",domain];
    sqlite3_stmt * stmt;
    
    if (db==nil)
        return result;
    
    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            sqlite_int64 index = sqlite3_column_int64(stmt, 0);
            char *data_cstr = (char*)sqlite3_column_text(stmt, 1);
            NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithCapacity:2];
            NSString *data = [self stringFromC:data_cstr];
            [resultDic setValue:data?:@"" forKey:RECORD_DATA_DATA_KEY];
            [resultDic setValue:@(index)?:@(-1) forKey:RECORD_DATA_INDEX_KEY];
            if (resultDic != nil) {
                [result addObject:resultDic];
            }
        }
        sqlite3_finalize(stmt);
    }
    return result;
}

/**
 * 搜索出指定域下特定条数的数据
 * @param domain 指定的域
 * @param deleteData 查出之后删除数据
 * @param count 最多查出多少条数据
 */
- (NSArray<NSDictionary *> *)searchDataWithDomain:(NSString *)domain deleteData:(BOOL)deleteData count:(NSInteger)count {
    NSMutableArray *result = [NSMutableArray array];;
    
    NSString * sqlQuery = [NSString stringWithFormat:@"SELECT * FROM %@ ORDER BY _id ASC LIMIT %d",domain,count];
    sqlite3_stmt * stmt;
    
    if (db==nil)
        return result;
    
    if (sqlite3_prepare_v2(db, [sqlQuery UTF8String], -1, &stmt, nil) == SQLITE_OK) {
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            sqlite_int64 index = sqlite3_column_int64(stmt, 0);
            char *data_cstr = (char*)sqlite3_column_text(stmt, 1);
            NSMutableDictionary *resultDic = [NSMutableDictionary dictionaryWithCapacity:2];
            NSString *data = [self stringFromC:data_cstr];
            [resultDic setValue:data?:@"" forKey:RECORD_DATA_DATA_KEY];
            [resultDic setValue:@(index)?:@(-1) forKey:RECORD_DATA_INDEX_KEY];
            if (resultDic != nil) {
                [result addObject:resultDic];
            }
        }
        sqlite3_finalize(stmt);
    }
    return result;
}


/**
 * 删除指定域下的所有数据
 * @param domain 指定的域
 */
- (void)clearDataWithDomain:(NSString *)domain {
    if (db==nil)
        return;
    
    NSString * sqlQuery = [NSString stringWithFormat:@"DELETE FROM %@",domain];
    [self execSql:sqlQuery];
}

/**
 * 删除指定域下特定条数的数据
 * @param domain 指定的域
 * @param count 最多删除多少条数据
 */
- (void)clearDataWithDomain:(NSString *)domain fromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex {
    if (db==nil)
        return;
    
    NSString * sqlQuery = [NSString stringWithFormat:@"DELETE FROM %@ WHERE _id <= %ld and _id >= %ld",domain,toIndex,fromIndex];
    [self execSql:sqlQuery];
}

@end
